package com.huang.transport.socket.server;

import com.huang.handler.RequestHandler;
import com.huang.hook.ShutdownHook;
import com.huang.prvider.ServiceProviderImpl;
import com.huang.registry.NacosServiceRegistry;
import com.huang.transport.AbstractRpcServer;
import com.huang.serializer.CommonSerializer;
import com.huangwei.factory.ThreadPoolFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/*
远程方法调用的提供者（服务端），Socketbio方式
 */
public class SocketRpcServer extends AbstractRpcServer {
    private final ExecutorService threadPool;
    private final CommonSerializer serializer;
    private final RequestHandler requestHandler = new RequestHandler();


    public SocketRpcServer(String host,int port){
        this(host,port,DEFAULT_SERIALIZER);
    }

    public SocketRpcServer(String host,int port,Integer serializer){
        this.host = host;
        this.prot = port;
        threadPool = ThreadPoolFactory.createDefaultThreadPool("socket-rpc-server");
        this.serviceRegistry = new NacosServiceRegistry();
        this.serviceProvider = new ServiceProviderImpl();
        this.serializer = CommonSerializer.getByCode(serializer);
        scanServices();
}


/*
启动服务端服务，绑定serversocket到指定端口，开启自动注销服务，监听到信号后，从线程池中选择一个线程执行处理方法
 */
    @Override
    public void start() {
        try (ServerSocket serverSocket = new ServerSocket()) {
            serverSocket.bind(new InetSocketAddress(host,prot));//这里参数拼错了port
            logger.info("服务器启动。。。");
            ShutdownHook.getShutdownHook().addClearAllHook();
            Socket socket;
            while ((socket = serverSocket.accept()) != null) {
                logger.info("消费者连接：{}：{}", socket.getInetAddress(), socket.getPort());
                threadPool.execute(new SocketRequestHandlerThread(socket, requestHandler, serializer));
            }
            threadPool.shutdown();
        } catch (IOException e) {
            logger.error("服务器启动时有错误发生", e);
        }
    }


}
